<!--
/**
* @name EBar
* @description 柱形图
* @author wind-lc
* @date 2020-06-09
* @param {Object} option 图表配置选项
* @param {Boolean} ready 图表数据加载完成
* @example <e-bar :option="" :ready=""></e-bar>
*/
-->
<template>
  <div ref="EChart"
       class="e-chart">
  </div>
</template>
<script>
import echarts from 'echarts'
import { mapGetters } from 'vuex'
export default {
  name: 'EBar',
  components: {},
  props: {
    // 图表选项
    option: {
      type: Object,
      required: true
    },
    // 图表数据加载完成
    ready: {
      type: Boolean,
      required: true
    }
  },
  data () {
    return {
      // 图表实例
      chart: null,
      // 图表选项
      chartOption: {
        // 鼠标悬停提示
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        }
      },
      // 屏幕变化事件
      resize: null
    }
  },
  computed: {
    ...mapGetters(['getCollapsed'])
  },
  watch: {
    // 监听侧边栏收缩
    getCollapsed: {
      handler (newV, oldV) {
        setTimeout(() => {
          this.chart.resize()
        }, 300)
      }
    },
    // 监听抽屉打开关闭
    ready: {
      handler (newV, oldV) {
        if (newV) {
          this.chart.hideLoading()
          this.chart.setOption(Object.assign(this.chartOption, this.option), true)
        } else {
          this.chartLoading()
        }
      },
      deep: true
    }
  },
  mounted () {
    this.init()
  },
  methods: {
    // 初始化
    init () {
      // 实例化图表
      this.chart = echarts.init(this.$refs.EChart)
      this.chartLoading()
      // 强行resize一次避免宽度bug
      const itemr = setTimeout(() => {
        this.chart.resize()
        clearTimeout(itemr)
      })
      // 响应屏幕变化
      // this.resize = this.chart.resize()
      addEventListener('resize', () => {
        const itemr = setTimeout(() => {
          this.chart.resize()
          clearTimeout(itemr)
        }, 300)
      })
    },
    // 图表加载中
    chartLoading () {
      // 设置选项
      this.chart.setOption(this.chartOption, true)
      // 等待加载
      this.chart.showLoading({
        text: '正在加载...',
        color: '#1890ff',
        textColor: '#333333',
        maskColor: '#ffffff',
        zlevel: 0
      })
    }
  },
  beforeDestroy () {
    // 销毁实例
    // this.chart.dispose()
    // addEventListener('mousemove', this.resize)
  }
}
</script>
<style lang="scss">
.e-chart {
  height: 100%;
}
</style>
